package cn.wolfcode.trip.admin.controller;

import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.query.StrategyQueryObject;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.service.IStrategyService;
import cn.wolfcode.trip.base.util.UploadUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @author by mycp
 * @Classname StrategyController
 * @Description TODO 大攻略处理器
 * @Date 2018/11/7 22:05
 */
@Controller
@RequestMapping("/strategy")
public class StrategyController {
    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private IRegionService regionService;
    @RequestMapping("/list")
    public String list(@ModelAttribute("qo") StrategyQueryObject qo, Model model){
        PageInfo pageInfo = strategyService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        // 查询所有的区域
        List<Region> list = regionService.list(null);
        model.addAttribute("regions", list);
        return "strategy/list";
    }


    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Strategy strategy, MultipartFile img){
        // 先判断前台是否有上传图片 且文件是否是图片格式
        // 定义文件上传文件的格式后缀名
        String fileType = "image";
        if (img != null && img.getContentType().startsWith(fileType)){
            // 先保存更新后的封面
            String coverUrl = UploadUtil.upload(img);
            // 将更改后的封面的url设置到strategy中替换掉旧的封面
            strategy.setCoverUrl(coverUrl);
        }
        strategyService.saveOrUpdate(strategy);
        return  "redirect:/strategy/list.do";
    }
}
